from datetime import datetime, timedelta
from typing import List, Dict, Tuple
from collections import defaultdict
import json

class TimeRangeCalculator:
    """时间范围计算器"""
    
    def __init__(self, hour_group_size : int = 24,base_time: datetime = None):
        """
        初始化
        
        Args:
            base_time: 基准时间，默认为当前时间
        """
        self.base_time = base_time or datetime.now()
        self.hour_group_size=hour_group_size
    
    def get_time_ranges(self, hours_back: int) -> List[Dict]:
        """
        获取时间范围
        
        Args:
            hours_back: 往前推的小时数
            
        Returns:
            List[Dict]: 时间范围列表
        """
        date_hours = defaultdict(list)
        
        for i in range(hours_back):
            target_time = self.base_time - timedelta(hours=i)
            date_str = target_time.strftime("%Y-%m-%d")
            hour = target_time.hour
            date_hours[date_str].append(hour)
        #print(date_hours)
        result = []
        for date_str, hours in sorted(date_hours.items(), reverse=True):
            #print(date_str)
            #print(hours)
            for i in range(0, len(hours), self.hour_group_size):
                group_hour = hours[i:i+self.hour_group_size]
                result.append({
                    'date': date_str,
                    'start_hour': min(group_hour),
                    'end_hour': max(group_hour),
                    'hours': sorted(group_hour)
                })
        
        return result
    
    def get_formatted_ranges(self, hours_back: int) -> List[str]:
        """
        获取格式化的时间范围字符串
        
        Args:
            hours_back: 往前推的小时数
            
        Returns:
            List[str]: 格式化的时间范围字符串
        """
        ranges = self.get_time_ranges(hours_back)
        formatted = []
        
        for item in ranges:
            formatted.append(f"{item['date']} {item['start_hour']}-{item['end_hour']}点")
        
        return formatted
    
    def get_time_range_dict(self, hours_back: int) -> Dict:
        """
        获取时间范围字典
        
        Args:
            hours_back: 往前推的小时数
            
        Returns:
            Dict: 包含详细信息的字典
        """
        ranges = self.get_time_ranges(hours_back)
        
        return {
            'base_time': self.base_time.strftime("%Y-%m-%d %H:%M:%S"),
            'hours_back': hours_back,
            'ranges': ranges,
            'total_days': len(ranges)
        }
    
    def get_sql_time_conditions(self, hours_back: int, time_column: str = "create_time") -> List[str]:
        """
        生成SQL时间条件
        
        Args:
            hours_back: 往前推的小时数
            time_column: 时间字段名
            
        Returns:
            List[str]: SQL条件列表
        """
        ranges = self.get_time_ranges(hours_back)
        conditions = []
        
        for item in ranges:
            date_str = item['date']
            year = date_str[:4]
            month = date_str[4:6]
            day = date_str[6:8]
            
            start_time = f"{year}-{month}-{day} {item['start_hour']:02d}:00:00"
            end_time = f"{year}-{month}-{day} {item['end_hour']:02d}:59:59"
            
            condition = f"({time_column} >= '{start_time}' AND {time_column} <= '{end_time}')"
            conditions.append(condition)
        
        return conditions

# 使用示例
if __name__ == "__main__":
    # 创建计算器实例
    calculator = TimeRangeCalculator(24)
    
    # 测试30小时
    print("=== 往前推30小时 ===")
    ranges = calculator.get_time_ranges(50)
    for item in ranges:
        print(f"日期: {item['date']}, 小时范围: {item['start_hour']}-{item['end_hour']}点")
    
    # print("\n=== 格式化输出 ===")
    # formatted = calculator.get_formatted_ranges(30)
    # for item in formatted:
    #     print(item)
    #
    # print("\n=== 详细信息 ===")
    # details = calculator.get_time_range_dict(30)
    # print(json.dumps(details, ensure_ascii=False, indent=2))
    #
    # print("\n=== SQL条件 ===")
    # sql_conditions = calculator.get_sql_time_conditions(30)
    # for condition in sql_conditions:
    #     print(condition)
